package agent.handler.bs;

import agent.container.HttpForwardClient;
import agent.container.TcpForwardClient;
import common.body.TcpTunnelBody;
import common.container.SwitchContainer;
import common.enums.ProtocolEnum;
import common.handler.AbstractBsHandler;
import common.packet.BsPacket;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;


/**
 * 开启本地代理
 * @author gitama
 * @version 1.0
 * @date 2022/12/05
 */
public class TcpTunnelOpenReqHandler extends AbstractBsHandler<TcpTunnelBody> {

    @Override
    public Class<TcpTunnelBody> bodyClass() {
        return TcpTunnelBody.class;
    }

    /**
     * 创建本地socket client
     *
     * @param packet         业务包
     * @param bsBody         具体内容包
     * @param channelContext 通道
     * @throws Exception
     */
    @Override
    public void handler(BsPacket packet, TcpTunnelBody bsBody, ChannelContext channelContext) throws Exception {
        String bsId = bsBody.getBsId();
        //这个值为token
        String clientToken = channelContext.getBsId();
        ChannelContext cc = null;
        SwitchContainer container;
        if (ProtocolEnum.HTTP.getCode().equals(bsBody.getProtocol())) {
            if (HttpForwardClient.clientTioConfig != null) {
                cc = Tio.getByBsId(HttpForwardClient.clientTioConfig, bsId);
            }
            container = new HttpForwardClient(bsBody.getHost(), bsBody.getPort(), bsId);
        } else {
            if (TcpForwardClient.clientTioConfig != null) {
                cc = Tio.getByBsId(TcpForwardClient.clientTioConfig, bsId);
            }
            container = new TcpForwardClient(bsBody.getHost(), bsBody.getPort(), bsId);
        }
        if (cc == null) {
            container.setClientToken(clientToken);
            container.start();
        }
    }

}
